package barcode

import (
	"bytes"
	"encoding/base64"
	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/code128"
	"image/png"
	"os"
	"strings"
)

func CreateBarFile(str string) string {
	bc, _ := code128.Encode(str)
	bar, _ := barcode.Scale(bc, 100, 50)
	file, _ := os.CreateTemp("./static/var/barcode", "barcode_tmp*.png")
	defer file.Close()
	png.Encode(file, bar)
	//jpeg.Encode(file,bar,nil)
	fileName := file.Name()
	filePath := fileName[1:]
	filePath = strings.ReplaceAll(filePath, "\\", "/")
	return filePath
}

func CreateBarBytes(str string) []byte {
	bc, e := code128.Encode(str)
	if e != nil {
		println("code128.Encode", e.Error())
	}
	bar, e := barcode.Scale(bc, 12*len(str)+35+10, 10)
	if e != nil {
		println("barcode.Scale", e.Error())
	}
	bf := bytes.NewBufferString("")
	e = png.Encode(bf, bar)
	if e != nil {
		println("png.Encode(bf,bar)", e.Error())
	}
	return bf.Bytes()
}

func CreateBarBase64(str string) string {
	data := CreateBarBytes(str)
	return base64.StdEncoding.EncodeToString(data)
}
